//
//  CZPlatformAnnouncementViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/16.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZPlatformAnnouncementViewController.h"
#import "CZWebNoticeViewController.h"
#import "CZNoticeCell.h"
static NSString * const plantform_announcement_cell = @"plantform_announcement_cell";

@interface CZPlatformAnnouncementViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *platformAnnouncementTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) LGRefreshView *refreshView;
@end

@implementation CZPlatformAnnouncementViewController
- (NSMutableArray *__nonnull)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _currentPage = 1;
    [self.platformAnnouncementTableView registerNib:[UINib nibWithNibName:@"CZNoticeCell" bundle:nil] forCellReuseIdentifier:plantform_announcement_cell];
    self.platformAnnouncementTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.platformAnnouncementTableView.estimatedRowHeight = 93;
    
    [self postNoticeData];
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.platformAnnouncementTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self.platformAnnouncementTableView.mj_footer setState:(MJRefreshStateIdle)];
                                                 _currentPage = 1;
                                                 [self postNoticeData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    self.platformAnnouncementTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self postNoticeData];
    }];
    self.platformAnnouncementTableView.mj_footer.hidden = YES;
    
    // Do any additional setup after loading the view from its nib.
}

#pragma mark- 获取公告
- (void)postNoticeData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/article/index",APP_HOST];
    [SVProgressHUD show];
    [GCZAFNetWorking POST:urlString params:@{@"article_type" : @4, @"page" : @(_currentPage)} success:^(NSDictionary *response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *arr = response[@"result"];
            if (!arr || arr.count < 1) {
                [self.platformAnnouncementTableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            if (_currentPage == 1) {
                self.dataArray = arr.mutableCopy;
            } else {
                for (NSDictionary *dic in arr) {
                    [self.dataArray addObject:dic];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.platformAnnouncementTableView reloadData];
                self.platformAnnouncementTableView.mj_footer.hidden = NO;
            });
        }
        [_refreshView endRefreshing];
        [self.platformAnnouncementTableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [self.platformAnnouncementTableView.mj_footer endRefreshing];
        [_refreshView endRefreshing];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZNoticeCell *cell = (CZNoticeCell *)[tableView dequeueReusableCellWithIdentifier:plantform_announcement_cell];
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    cell.noticeTitleLabel.text = dataDic[@"title"];
    cell.timeLabel.text = dataDic[@"article_time"];
    
    NSMutableString *dateStr = [(NSString *)dataDic[@"article_time"] mutableCopy];
    [dateStr appendString:@" +0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSDate *articleDate = [formatter dateFromString:[dateStr copy]];
    
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:articleDate];
    
    if (timeInterval < 60) {
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%f秒前", timeInterval];
    } else if (timeInterval > 60 && timeInterval < 3600) {
        NSInteger minute = timeInterval / 60;
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%d分钟前", minute];
    } else if (timeInterval > 3600 && timeInterval < 86400) {
        NSInteger hour = timeInterval / 3600;
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%d小时前", hour];
    } else if (timeInterval > 86400 && timeInterval < 2592000) {
        NSInteger day = timeInterval / 86400;
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%d天前", day];
    } else if (timeInterval > 2592000 && timeInterval < 2592000 * 365) {
        NSInteger month = timeInterval / 2592000;
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%d个月前", month];
    } else if (timeInterval > 2592000 * 365) {
        NSInteger year = timeInterval / (2592000 * 365);
        cell.timeIntervalLabel.text = [NSString stringWithFormat:@"%d年以前", year];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    CZWebNoticeViewController *webVC = [[CZWebNoticeViewController alloc] init];
    webVC.type = @"平台公告";
    webVC.articleID = dataDic[@"article_id"];
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
